// src/stores/auth.js
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null, // 当前用户信息
    isAuthenticated: false, // 是否已认证
  }),
  actions: {
    // 登录操作
    login(user) {
      this.user = user;
      this.isAuthenticated = true;
      // 将用户信息存储到 localStorage
      localStorage.setItem('user', JSON.stringify(user));
      localStorage.setItem('isAuthenticated', JSON.stringify(true));
    },
    // 注销操作
    logout() {
      this.user = null;
      this.isAuthenticated = false;
      // 从 localStorage 中移除用户信息和认证状态
      localStorage.removeItem('user');
      localStorage.removeItem('isAuthenticated');
    },
  },
  getters: {
    // 从 localStorage 中恢复用户信息
    storedUser: (state) => {
      return JSON.parse(localStorage.getItem('user')) || state.user;
    },
    // 从 localStorage 中恢复认证状态
    storedIsAuthenticated: (state) => {
      return JSON.parse(localStorage.getItem('isAuthenticated')) || state.isAuthenticated;
    },
  },
});